import React, {PropsWithChildren, useState} from 'react'
import {Text, View} from "@tarojs/components";
import styles from "./SelectGoodsPopup.module.sass"
import {Button, Popup} from "@nutui/nutui-react-taro";
import QueryGoodsList, {QueryGoodsListExistedItem, QueryGoodsListProps} from "./QueryGoodsList";
import {AddOrderItemKey} from "../apis/GoodsApi";

export interface SelectGoodsPopupProps extends PropsWithChildren, QueryGoodsListProps {
    visible: boolean
    onClose: () => void
    onConfirm: (goodsIdList: AddOrderItemKey[]) => Promise<void>
    existedGoodsList?: QueryGoodsListExistedItem[]
}

const SelectGoodsPopup: React.FC<SelectGoodsPopupProps> = (props) => {
    const [selectedGoodsIdList, setSelectedGoodsIdList] = useState<AddOrderItemKey[]>([])
    const [loading, setLoading] = useState(false)
    return <>
        <Popup visible={props.visible} onClose={props.onClose} position={"bottom"}>
            <View className={styles.container}>
                <View className={styles.topBar}>
                    <Button fill={"none"} onClick={() => {
                        props.onClose()
                    }}>取消</Button>
                    <Text>选择货品{selectedGoodsIdList.length ? `(${selectedGoodsIdList.length})` : ""}</Text>
                    <Button type={"primary"} loading={loading} fill={"none"} onClick={async () => {
                        try {
                            setLoading(true)
                            await props.onConfirm(selectedGoodsIdList)
                            props.onClose()
                        } finally {
                            setLoading(false)
                        }
                    }}>确定</Button>
                </View>
                <View className={styles.goodsListWrapper}>
                    {props.visible && <QueryGoodsList key={props.visible.toString()} {...props}
                                                      existedGoodsList={props.existedGoodsList}
                                                      onSelectedGoodsIdListChange={it => setSelectedGoodsIdList(it)}/>}
                </View>
            </View>
        </Popup>
    </>
}

export default SelectGoodsPopup


